package com.xiaojiezhu.shiro.spring.shiro;

import com.xiaojiezhu.shiro.spring.bean.UserInfo;
import com.xiaojiezhu.shiro.spring.dao.UserDao;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @Author 朱小杰
 * 时间 2017-08-06 .23:04
 * 说明 ...
 */
//@Service
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserDao userDao;

    /**
     * 用于权限的认证，加载权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = principals.getPrimaryPrincipal().toString();
        List<String> roles = userDao.findRolesByUserName(userName);
        List<String> permissions = userDao.findPermissionsByUserName(userName);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(new HashSet<>(roles));//加载角色
        authorizationInfo.setStringPermissions(new HashSet<>(permissions));//加载权限
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String userName = upToken.getUsername();
        String password = new String((char[])upToken.getCredentials());

        UserInfo queryUser = userDao.findByUserName(userName);
        if(queryUser == null){
            throw new IncorrectCredentialsException();
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(queryUser.getName(),queryUser.getPassword(),queryUser.getName());
        //不需要手动去验证密码，只需要手动调用这个方法，就可让让shiro自动验证密码，必须调用这个方法，因为shiro会标志密码是否校验过，如果不调用这个方法，则会被shiro抛出异常
        assertCredentialsMatch(token,authenticationInfo);
        return authenticationInfo;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
